<template>
  <div class="course-shop">
    <div class="page-header">
      <h2>课程购买</h2>
      <p>浏览和购买您感兴趣的课程</p>
    </div>

    <div class="course-list" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="8" v-for="course in courseList" :key="course.name" class="course-item">
          <el-card class="course-card" shadow="hover">
            <div class="course-info">
              <h3 class="course-name">{{ course.name }}</h3>
              <div class="course-details">
                <div class="detail-item">
                  <span class="label">课程状态：</span>
                  <el-tag :type="course.state === 1 ? 'success' : 'danger'">
                    {{ course.state === 1 ? '可购买' : '不可购买' }}
                  </el-tag>
                </div>
                <div class="detail-item">
                  <span class="label">课程价格：</span>
                  <span class="price">¥{{ course.price }}</span>
                </div>
              </div>
              
              <div class="purchase-form" v-if="course.state === 1">
                <el-form :model="purchaseForms[course.name]" :rules="purchaseRules" ref="purchaseFormRefs">
                  <el-form-item label="订单来源" prop="billForm">
                    <el-select v-model="purchaseForms[course.name].billForm" placeholder="请选择订单来源">
                      <el-option label="微信" :value="1"></el-option>
                      <el-option label="支付宝" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="配送方式" prop="billWay">
                    <el-select v-model="purchaseForms[course.name].billWay" placeholder="请选择配送方式">
                      <el-option label="自提" :value="1"></el-option>
                      <el-option label="配送" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
                
                <el-button 
                  type="primary" 
                  @click="handlePurchase(course)"
                  :loading="purchasing[course.name]"
                  class="purchase-btn"
                >
                  立即购买
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && courseList.length === 0" description="暂无课程可购买" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCourseShop, purchaseCourse } from '@/api/course'

// 响应式数据
const loading = ref(false)
const courseList = ref([])
const purchasing = reactive({})

// 购买表单数据
const purchaseForms = reactive({})
const purchaseFormRefs = ref({})

// 表单验证规则
const purchaseRules = {
  billForm: [
    { required: true, message: '请选择订单来源', trigger: 'change' }
  ],
  billWay: [
    { required: true, message: '请选择配送方式', trigger: 'change' }
  ]
}

// 获取用户信息
const getUserInfo = () => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    try {
      return JSON.parse(userInfo)
    } catch (e) {
      console.error('解析用户信息失败:', e)
      return null
    }
  }
  return null
}

// 获取课程列表
const fetchCourseList = async () => {
  try {
    loading.value = true
    const response = await getCourseShop()
    
    if (response.code === 200) {
      courseList.value = response.data || []
      
      // 初始化每个课程的购买表单
      courseList.value.forEach(course => {
        purchaseForms[course.name] = {
          billForm: null,
          billWay: null
        }
        purchasing[course.name] = false
      })
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 处理购买
const handlePurchase = async (course) => {
  const formData = purchaseForms[course.name]
  
  // 验证表单
  if (!formData.billForm || !formData.billWay) {
    ElMessage.warning('请完善购买信息')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要购买课程"${course.name}"吗？\n价格：¥${course.price}`,
      '确认购买',
      {
        confirmButtonText: '确定购买',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    purchasing[course.name] = true
    
    // 获取用户信息
    const userInfo = getUserInfo()
    if (!userInfo) {
      ElMessage.error('用户信息获取失败，请重新登录')
      return
    }
    
    // 构建购买数据
    const purchaseData = {
      name: course.name,
      price: course.price,
      state: course.state,
      billForm: formData.billForm,
      billWay: formData.billWay,
      userInfo: userInfo.value || userInfo.account || ''
    }
    
    const response = await purchaseCourse(purchaseData)
    
    if (response.code === 200) {
      ElMessage.success('购买成功！')
      
      // 重置表单
      purchaseForms[course.name] = {
        billForm: null,
        billWay: null
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('购买失败:', error)
      ElMessage.error('购买失败，请重试')
    }
  } finally {
    purchasing[course.name] = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCourseList()
})
</script>

<style scoped>
.course-shop {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.course-list {
  margin-bottom: 20px;
}

.course-item {
  margin-bottom: 20px;
}

.course-card {
  height: 100%;
  transition: all 0.3s ease;
}

.course-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.course-info {
  padding: 10px 0;
}

.course-name {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
  line-height: 1.4;
}

.course-details {
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 500;
  color: #666;
  margin-right: 8px;
  min-width: 80px;
}

.price {
  font-size: 16px;
  font-weight: 600;
  color: #e6a23c;
}

.purchase-form {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

.purchase-form .el-form-item {
  margin-bottom: 15px;
}

.purchase-form .el-form-item:last-child {
  margin-bottom: 0;
}

.purchase-btn {
  width: 100%;
  margin-top: 10px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #666;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-empty) {
  background: white;
  border-radius: 8px;
  padding: 40px;
}
</style>
